<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-if="open" v-model="open" width="1200px" append-to-body>
    <div v-loading="loading">
      <el-form ref="form" :model="form" :rules="rules" label-width="90px" :inline="true">
        <el-form-item label="客户:" prop="clientId">
          <el-select v-model="form.clientId" filterable clearable remote reserve-keyword placeholder="请选择客户"
            @change="customerChange" :remote-method="(query) => remoteMethod(query, 'supplier', 'supplierName')"
            :loading="loading">
            <el-option v-for="item in supplierOptions" :key="item.id" :label="item.supplierName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟单人" prop="preparedId">
          <el-select v-model="form.preparedId" filterable clearable remote reserve-keyword placeholder="请选择跟单人"
            :loading="loading" @change="handleQuery">
            <el-option v-for="item in userList" :key="item.value" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="报价状态:" prop="quotationStatus">
          <el-select v-model="form.quotationStatus" clearable reserve-keyword placeholder="报价状态">
            <el-option v-for="item in quote_status" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟单时间" prop="quotationTime">
          <el-date-picker v-model="form.quotationTime" style="width: 240px" value-format="YYYY-MM-DD hh:mm:ss"
            type="date" placeholder="选择跟单时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="方案:" prop="schemeId">
          <el-select v-model="form.schemeId" filterable remote reserve-keyword placeholder="请选择方案"
            @change="schemeChange" :remote-method="(query) => remoteMethod(query, 'quotationScheme', 'schemeName')"
            :loading="loading">
            <el-option v-for="item in quotationSchemeOptions" :key="item.id" :label="item.schemeName"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="报价单号:" prop="quotationCode">
          <el-input disabled v-model="form.quotationCode" placeholder="自动生成"></el-input>
        </el-form-item>
        <el-form-item label="联系人:" prop="quotationName" style="width:100%">
          <el-input v-model="form.quotationName" placeholder="请选择联系人"></el-input>
        </el-form-item>
        <el-form-item label="进展备注:" prop="remark" style="width:100%">
          <el-input type="textarea" :rows="4" v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import modelMixin from '@/mixins/modelMixin'
import quotation, { getQuotationCode } from '@/api/goods/quotation'
import { getSupplier } from '@/api/goods/supplier'
import { listUser } from '@/api/system/user';
export default {
  name: 'addForm',
  mixins: [modelMixin],
  data() {
    return {
      open: false,
      title: '添加报价单',
      funcObj: quotation,
      multiple: false,
      selectedRows: [],
      form: {
        quotationStatus: 0
      },
      supplierOptions: [],//客户
      quotationSchemeOptions: [],//方案
      queryParams: {
        categoryId: '',
        categoryName: ''
      },
      active: 1,
      baseInput: 200,
      data: [],
      dateRange: [],
      dataSource: [],
      loading: false,
      quote_status: [],//报价状态
      userList: [],//跟单人列表
      rules: {
        clientId: [
          { required: true, message: "请选择客户", trigger: "change" },
        ],
        quotationTime: [
          { required: true, message: "请选择跟单时间", trigger: "change" },
        ],
        quotationStatus: [
          { required: true, message: "请选择报价状态", trigger: "change" },
        ],
      },
    };
  },

  methods: {
    edit(row) {
      this.open = true;
      this.title = '报价跟进',
        this.form = {}
      this.dataSource = []
      this.listQuotationSchemeAll().then(() => {
        this.quotationSchemeOptions = this.quotationSchemeList;
      });
      this.getSupplierAllList(1).then(() => {
        this.supplierOptions = this.supplierList;
      });
      this.listSysUser()
      this.getDicts('quote_status');
      this.getDetail(row)
    },
    detailAfter() {
      this.dataSource = this.form.quotationItemVoList.map(v => {
        return {
          ...v,
          packImg: v.jzgGoodsVo && v.jzgGoodsVo.packImg || '',
          goodsName: v.jzgGoodsVo && v.jzgGoodsVo.goodsName || '',
          brandName: v.jzgGoodsVo && v.jzgGoodsVo.brandName || '',
        }
      })
    },
    // 获取报价单号
    addInit() {
      getQuotationCode().then(res => {
        this.form.quotationCode = res.data || res.msg;
      })
    },
    cancel() {
      this.open = false;
    },
    categoryChange(value) {
      this.form.categoryId = value;
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
      this.multiple = val.length > 0;
    },
    selectHandle(row) {
      return 1;
    },
    handleAdd() {
      this.$refs.selectMaterialForm.show();
    },

    selectOk(data) {
      this.dataSource = data.map(v => {
        return {
          ...v,
          goodsId: v.id,
          surrogateStatus: v.supplyMode,
          shelfStatus: v.auditStatus,
          costPrice: v.costPrice,
          wholesalePrice: v.wholesalePrice
        }
      });
    },
    remoteMethod(query, listKey, key) {
      const optionKey = listKey + 'Options';
      if (query !== '') {

        this[optionKey] = this[listKey + 'List'].filter(item => {
          return item[key].toLowerCase()
            .indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this[optionKey] = this[listKey + 'List'];
      }

    },

    classifyForm() {
      this.form.quotationItemList = this.dataSource
      // 价格
      this.form.averagePrice = this.dataSource.reduce((total, item) => {
        return total + +item.wholesalePrice
      }, 0) / this.dataSource.length
      // 金额
      this.form.quotationPrice = this.dataSource.reduce((total, item) => {
        return total + +item.wholesalePrice
      }, 0)
      console.log('this.form :>> ', this.form);
    },

    /**
     * @批量删除
     */
    handleBatchDelete() {
      if (this.selectedRows.length == 0) {
        this.$modal.msgError('请选择要删除的数据');
        return;
      }
      var ids = this.selectedRows.map(item => item.goodsId).join(',');
      this.$modal.confirm('是否删除选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataSource = this.dataSource.filter(item => !ids.includes(item.goodsId));
      }).catch(() => {
        this.$modal.messageError({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    customerChange(value) {
      if (!value) {
        this.form.quotationName = '';
        return;
      }
      getSupplier(value).then(res => {
        if (res.data.supplierContactList.length > 0) {
          this.form.quotationName = res.data.supplierContactList[0].name;
        }
      })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        const keyArr = ['costPrice', 'wholesalePrice', 'number']
        if (keyArr.includes(column.property)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!Number.isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = '-'
        }
      })

      return sums
    },
    // 获取后台用户
    listSysUser() {
      listUser().then(res => {
        this.userList = res.rows
      }).catch(err => {
        console.log(err)
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>